// pages/goods/details/components/goods-buy-popup/index.js
const userModel = require('../../../../../model/user');
const { submitOrder, updateOrderStatus } = require('../../../../../services/order/orderConfirm');
Component({
  properties: {
    showPopup: {
      type: Boolean,
      value: false
    },
    product: {
      type: Object,
      value: {}
    }
  },

  data: {
    quantity: 1,  // 初始购买数量
    computedPrice: 0, // 计算后的总价格
    deliveryMethod: 'delivery',  // 默认购买方式
    isScannedCabinet: false, // 是否扫码进入
    role: 'GUEST'
  },

  lifetimes: {
    attached() {
      this.checkScannedCabinet();
      const user = userModel.getUserData();
      this.setData({
        role: user.info.role
      });
    }
  },

  methods: {
    // **检查是否是扫码进入**
    checkScannedCabinet() {
      const scannedCabinetUserId = wx.getStorageSync('scannedCabinetUserId');

      this.setData({
        isScannedCabinet: !!scannedCabinetUserId
      });

      console.log("✅ isScannedCabinet:", this.data.isScannedCabinet);
    },

    // 更新总价格
    updateComputedPrice() {
      const user = userModel.getUserData();
      const product = this.properties.product;
      if (!product || !product.price) return;

      // **根据用户身份动态计算价格**
      const price = (user.info.role === 'GUEST') ? product.price : product.memberPrice;

      this.setData({
        computedPrice: price * this.data.quantity
      });

      console.log("✅ 计算后的价格：", this.data.computedPrice);
    },

    // 关闭弹窗
    handleClosePopup() {
      this.triggerEvent('closePopup');
    },

    // 减少购买数量
    decreaseQuantity() {
      if (this.data.quantity > 1) {
        this.setData({
          quantity: this.data.quantity - 1
        });
      }
    },

    // 增加购买数量
    increaseQuantity() {
      this.setData({
        quantity: this.data.quantity + 1
      });
    },

    // 选择购买方式
    selectDeliveryMethod(e) {
      const method = e.currentTarget.dataset.value;
      this.setData({
        deliveryMethod: method
      });
    },

    // 确认下单
    async handleConfirmOrder() {
      this.updateComputedPrice();
      const { deliveryMethod, quantity, computedPrice } = this.data;
      const product = this.properties.product;

      // 如果选择酒柜取货，直接进行微信支付
      if (deliveryMethod === 'pickup') {
        wx.showLoading({ title: '提交中...' });

        try {
          const user = userModel.getUserData();

          // 调用提交订单接口，获取支付参数
          const wxPayArgs = await submitOrder({
            userId: user.info.id,
            totalPrice: computedPrice,
            shippingAddressId: null, // 酒柜取货无需地址
            paymentMethod: "wechatPay",
            parentId: user.info.parentId,
            openid: user.info.openid,
            wineId: product.id,
            wineName: product.name,
            wineNum: quantity,
            deliveryMethod: 'pickup'
          });

          if (!wxPayArgs) {
            wx.showToast({
              title: '提交订单失败',
              icon: 'error'
            });
            return;
          }

          const { orderId, ...payArgs } = wxPayArgs;

          // 调用微信支付
          wx.requestPayment({
            ...payArgs,
            success: (res) => {
              wx.showToast({
                title: '支付成功',
                icon: 'success'
              });
              updateOrderStatus(orderId, "PAYED");
              wx.navigateTo({ url: '/pages/order/pay-result/index' });
            },
            fail: (err) => {
              console.error(err);
              if (err.errMsg === "requestPayment:fail cancel") {
                wx.showToast({
                  title: '取消支付',
                  icon: 'none'
                });
                updateOrderStatus(orderId, "CANCELED");
              } else {
                wx.showToast({
                  title: '支付失败',
                  icon: 'error'
                });
                updateOrderStatus(orderId, "FAIL");
              }
            },
            complete: () => {
              wx.hideLoading();
            }
          });
        } catch (error) {
          console.error('订单提交失败', error);
          wx.showToast({
            title: '提交订单失败',
            icon: 'error'
          });
          wx.hideLoading();
        }
      } else {
        // 商城发货逻辑，触发父组件事件
        const orderData = {
          product: this.properties.product,
          quantity: this.data.quantity,
          deliveryMethod: this.data.deliveryMethod
        };
        this.triggerEvent('confirmOrder', orderData);
        this.handleClosePopup();
      }
    }
  }
});
